package com.bw.i_video

import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.LayoutInflater
import android.view.Gravity
import android.view.View
import android.widget.CheckBox
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.viewpager2.widget.ViewPager2
import com.bw.home.HomeFragment
import com.bw.live.LiveFragment
import com.bw.mine.MineFragment
import com.bw.openlive.OpenLiveFragment
import com.bw.screeningroom.ScreeningRoomFragment
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.therouter.TheRouter
import com.therouter.router.Route
import com.tencent.mmkv.MMKV

@Route(path = "/app/MainActivity")
class MainActivity : AppCompatActivity() {
    private lateinit var viewPager: ViewPager2
    private lateinit var bottomNav: BottomNavigationView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        viewPager = findViewById(R.id.view_pager)
        bottomNav = findViewById(R.id.bottom_nav)
//        bottomNav.itemIconTintList = null
//        bottomNav.itemTextColor = ContextCompat.getColorStateList(this, R.color.selector_color)//文字颜色



        setupViewPager()
        setupNavigation()

        // 恢复上次的页面
        val lastPage = savedInstanceState?.getInt("current_page") ?: 0
        viewPager.setCurrentItem(lastPage, false)

        // 展示用户协议与隐私政策弹窗（仅首次）
        showPrivacyDialogIfNeeded()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        // 保存当前页面
        outState.putInt("current_page", viewPager.currentItem)
    }
    private fun setupViewPager() {
        // 创建Fragment实例
        val fragments = listOf(
            HomeFragment(),
            ScreeningRoomFragment(),
            LiveFragment(),
            OpenLiveFragment(),
            MineFragment()
        )

        // 配置ViewPager2
        viewPager.adapter = MainBottomAdapter(this, fragments)

        // 设置页面缓存（左右各缓存1页 + 当前页 = 3页）
        viewPager.offscreenPageLimit = 2

        // 禁用用户滑动（可选）
        // viewPager.isUserInputEnabled = false
    }

    private fun setupNavigation() {
        // 底部导航点击事件
        bottomNav.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.menu_home -> viewPager.setCurrentItem(0, false)
                R.id.menu_video -> viewPager.setCurrentItem(1, false)
                R.id.menu_live -> viewPager.setCurrentItem(2, false)
                R.id.open_Live -> viewPager.setCurrentItem(3, false)
                R.id.menu_mine -> viewPager.setCurrentItem(4, false)
            }
            true
        }

        // ViewPager页面切换监听
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                bottomNav.menu.getItem(position).isChecked = true
            }
        })
    }

    private fun showPrivacyDialogIfNeeded() {
        val kv = MMKV.defaultMMKV()
        val agreed = kv?.getBoolean("privacy_agreed", false) == true
        if (agreed) return

        val dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_privacy_policy, null)
        val tvLinks = dialogView.findViewById<TextView>(R.id.tv_links)
        val cbAgree = dialogView.findViewById<CheckBox>(R.id.cb_agree)

        val userText = getString(R.string.privacy_user_agreement)
        val policyText = getString(R.string.privacy_policy)
        val full = "$userText 和 $policyText"
        val span = SpannableString(full)

        val userStart = 0
        val userEnd = userText.length
        val policyStart = full.indexOf(policyText)
        val policyEnd = policyStart + policyText.length

        span.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                // 这里可跳转到用户协议页面
                // TheRouter.build("/web/UserAgreement").navigation(this@MainActivity)
            }
        }, userStart, userEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

        span.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                // 这里可跳转到隐私政策页面
                // TheRouter.build("/web/PrivacyPolicy").navigation(this@MainActivity)
            }
        }, policyStart, policyEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

        tvLinks.text = span
        tvLinks.movementMethod = LinkMovementMethod.getInstance()

        val dialog = AlertDialog.Builder(this)
            .setView(dialogView)
            .setCancelable(false)
            .setPositiveButton(R.string.privacy_agree, null)
            .setNegativeButton(R.string.privacy_disagree) { _, _ ->
                finish()
            }
            .create()

        dialog.setOnShowListener {
            dialog.window?.setGravity(Gravity.CENTER)
            val positive = dialog.getButton(AlertDialog.BUTTON_POSITIVE)
            positive.isEnabled = false
            cbAgree.setOnCheckedChangeListener { _, isChecked ->
                positive.isEnabled = isChecked
            }
            positive.setOnClickListener {
                if (cbAgree.isChecked) {
                    kv?.putBoolean("privacy_agreed", true)
                    dialog.dismiss()
                }
            }
        }
        dialog.show()
    }
}